﻿Imports DotNetNuke.Entities.Portals
Imports DotNetNuke.Security.Roles
Imports System.Collections.Generic
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Web
Imports System.Web.Services
Imports System.Web.SessionState

Namespace WillStrohl.Modules.CodeCamp

    Public Class Roles
        Implements System.Web.IHttpHandler, IRequiresSessionState

        Private p_Query As String = Null.NullString

        Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

            context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
            context.Response.ContentType = "text/plain"

            If Not context.Request.Params("query") Is Nothing Then
                Me.p_Query = context.Request.Params("query").ToString.ToLower
            End If

            If IsEditMode() Then
                context.Response.Write(Me.GetRoleNames)
            Else
                context.Response.Write("Not Authorized")
            End If

        End Sub

        Private Function GetRoleNames() As String

            Dim strReturn As String = Null.NullString
            Dim strPattern As String = String.Concat(".*", Me.p_Query, ".*")
            Dim collStr As New List(Of String)

            Dim pStgs As PortalSettings = PortalController.GetCurrentPortalSettings
            Dim arrRoles As ArrayList = New ArrayList()
            Dim objRoles As RoleController = New RoleController

            arrRoles = objRoles.GetPortalRoles(pStgs.PortalId)

            For Each role As RoleInfo In arrRoles
                If Regex.IsMatch(role.RoleName, strPattern, RegexOptions.IgnoreCase) Then
                    collStr.Add(role.RoleName)
                End If
            Next

            strReturn = CodeCampController.GenerateJSON("suggestions", collStr)
            strReturn = Regex.Replace(strReturn, "\{", String.Concat("{ ", String.Format("query:'{0}',", Me.p_Query)))

            Return strReturn

        End Function

        ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
            Get
                Return False
            End Get
        End Property

    End Class

End Namespace